package com.lagou.rabbitmqtask.controller;

import com.lagou.rabbitmqtask.pojo.Order;
import com.lagou.rabbitmqtask.service.OrderService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Controller
@CrossOrigin
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RabbitTemplate template;

    @Autowired
    private OrderService orderService;

    @RequestMapping("/index")
    public String index() {

        return "index";
    }

    @RequestMapping(value = "order/{order_id}")
    public String order(@PathVariable String order_id, Model model) {
        Order order = new Order(order_id, new Date());
        orderService.addOrder(order);
        this.template.convertAndSend("exchange.task61.topay", "routing.key", order_id.getBytes());
        model.addAttribute("order_id", order_id);
        return "wait";
    }

    @RequestMapping("/success/{order_id}")
    public String success(@PathVariable String order_id, Model model) {
        orderService.updateOrder(order_id, "已支付");
        this.template.convertAndSend("exchange.task61.pay", "routing.key", order_id.getBytes());
        model.addAttribute("order_id", order_id);
        return "success";
    }

    @RequestMapping("/getList/{order_id}")
    public String getList(@PathVariable String order_id, Model model) {
        orderService.updateOrder(order_id, "已超时");
        this.template.convertAndSend("exchange.task61.unpay", "routing.key", order_id.getBytes());
        final List<Order> orderList = orderService.getOrderList();
        model.addAttribute("orderList", orderList);
        return "list";
    }
}
